package com.burgeon.backend.EnterpriseWeChat.service.Impl;

import com.burgeon.backend.EnterpriseWeChat.mappers.EWEmpMapper;
import com.burgeon.backend.EnterpriseWeChat.rest.QueryErpEmpData;
import com.burgeon.backend.EnterpriseWeChat.service.EWEmpService;
import com.burgeon.backend.EnterpriseWeChat.service.EWInfoService;
import com.burgeon.backend.EnterpriseWeChat.utils.WXBizMsgCrypt;
import com.burgeon.backend.SHOP.entity.EmpData;
import com.burgeon.backend.SHOPBACKEND.service.ex.UploadException;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class EWEmpServiceImpl implements EWEmpService {
    private final static Log logger = LogFactory.getLog(EWEmpService.class);
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private EWInfoService ewInfoService;
    @Autowired
    private EWEmpMapper ewEmpMapper;

    /**
     *
     * @param req
     * @param res
     * @param CORP_ID
     * @param SUITE_TOKEN
     * @param SUITE_ENCODING_AES_KEY
     * @param msgSignature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @param token
     */
    @Override
    public void WXSaaSCallback(HttpServletRequest req, ServletResponse res, String CORP_ID,
                               String SUITE_TOKEN, String SUITE_ENCODING_AES_KEY,
                               String msgSignature, String timestamp, String nonce,
                               String echostr,String token) {
        String postData = null;
        try {
            InputStream inputStream = req.getInputStream();
            postData = IOUtils.toString(inputStream, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        String result;

        try {
            //=======验证回调url有效性=======
            WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(SUITE_TOKEN,
                    SUITE_ENCODING_AES_KEY, CORP_ID);//注意是CORP_ID
            if (null != echostr) {
                result = wxBizMsgCrypt.VerifyURL(msgSignature, timestamp, nonce, echostr);
                System.err.println(result);
                res.getWriter().write(result);    //对echostr参数解密并原样返回echostr明文(不能加引号，不能带bom头，不能带换行符)
                return;
            }

            String a = wxBizMsgCrypt.DecryptMsg(msgSignature, timestamp, nonce, postData);
            System.err.println(a);
            Map<String, String> map = convertToMap(a);
            //消息类型

            System.err.println(map.get("ToUserName"));
            switch (map.get("MsgType")){
                case "text":
                    System.err.println(map.get("Content"));
                    break;
                case "image":
                    System.err.println(map.get("PicUrl"));
                    break;
                case "voice":
                case "video":
                    System.err.println(map.get("MediaId"));
                    break;
                case "location":
                    System.err.println(map.get("Label"));
                    System.err.println(map.get("Location_X"));
                    System.err.println(map.get("Location_Y"));
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成 全部员工企业微信
     * @param account
     */
    @Override
    public void MassProductionEWEmp(String account) {
        Info info = GetInfo(account);

        QueryErpEmpData queryErpEmpData = new QueryErpEmpData(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            ArrayList<EmpData> data = queryErpEmpData.getData();
            for (EmpData empData :data){
                ewInfoService.createEWEmp(empData.getCode(),empData.getName(),empData.getPhone(),account);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传导购图片
     * @param file
     * @param token
     */
    @Override
    public String uploadImg(MultipartFile file, String token,String empId) {
        if (null == file || file.isEmpty()) {
            System.out.println("文件为空");
            throw new UploadException("文件为空");
        }else if(null == token || token.isEmpty()){
            throw new UploadException("客户标识为空");
        }else if(null == empId || empId.isEmpty()){
            throw new UploadException("导购为空");
        }


        String fileName = file.getOriginalFilename(); //文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名
        String filePath = "//root//code//img//employee//" + token+"//"; // 上传后的路径
        long now = System.currentTimeMillis();
        fileName =now+suffixName; // 新文件名
        String url ="http://lfwdcdn.cloudsmicro.com/img/employee/"+token+"/"+fileName;
        filePath=filePath+fileName;//上传的完整路径
        saveFile(file,filePath);
        String headImg = ewEmpMapper.getEmpHeadImg(empId,token);
        if(headImg !=null){
            ewEmpMapper.updateEmpHeadImg(empId,token,url);
        }else {
            Integer row = ewEmpMapper.addEmpHeadImg(empId,url,token);
            if(row ==0){
                logger.info("上传图片失败======="+empId);
                throw new UploadException("上传图片失败");
            }
        }

        return url;

    }

    /**
     * 上传头像
     * @param empId
     * @param token
     * @return
     */
    @Override
    public String getEmpHeadImg(String empId, String token) {
        String headImg = ewEmpMapper.getEmpHeadImg(empId, token);
        if(headImg == null){
            headImg="http://lfwdcdn.cloudsmicro.com/img/employee/lfwd/default.png";
        }
        System.err.println(headImg);
        return headImg;
    }

    //保存文件
    private void saveFile(MultipartFile multipartFile,String filePath) {
        File dest = new File(filePath);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new com.burgeon.backend.service.ex.UploadException("系统错误");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw new com.burgeon.backend.service.ex.UploadException("系统错误");
        }
    }



    private Info GetInfo(String token) {
        return accountMapper.GetTokenData(token);
    }


    /**
     * 转换简单的xml to map
     *
     * @param xml xml
     * @return map
     */
    private static Map<String, String> convertToMap(String xml) {
        Map<String, String> map = new LinkedHashMap<String, String>();
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader sr = new StringReader(xml);
            InputSource is = new InputSource(sr);
            Document document = db.parse(is);

            Element root = document.getDocumentElement();
            if (root != null) {
                NodeList childNodes = root.getChildNodes();
                if (childNodes != null && childNodes.getLength() > 0) {
                    for (int i = 0; i < childNodes.getLength(); i++) {
                        Node node = childNodes.item(i);
                        if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
                            map.put(node.getNodeName(), node.getTextContent());
                        }
                    }
                }
            }
        } catch (DOMException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
}
